Import yimWork

Class yimSoundManager
	
	Field channels:List<yimSoundChannel> = New List<yimSoundChannel>()
	Field sounds:StringMap<yimSoundSound> = New StringMap<yimSoundSound>()
	
	Field nextChannel:Int = 0
	Field maxChan:Int
	Field curPlay:yimSoundSound[]
	
	Method New(channels:Int=16)
		maxChan = 0
		For Local i:= 0 Until 8
			If ChannelState(i) = 0
				SetChannelVolume(i, 0.5)
				maxChan += 1
			EndIf
		Next
		curPlay = New yimSoundSound[maxChan]
	End
	
	Method LoadSoundFile:yimSoundSound(sndFile:String, name:String)
		Local tSound:yimSoundSound = New yimSoundSound(LoadSound(sndFile), name)
		sounds.Set(name, tSound)
		Return tSound
	End
	
	Method PlayYimSound(name:String)
		 PlayYimSound(sounds.Get(name))
	End
	
	Method PlayYimSound(snd:yimSoundSound)
		If ChannelState(nextChannel) = 1 And curPlay[nextChannel] <> Null
			StopChannel(nextChannel)
			curPlay[nextChannel].plays -= 1
		EndIf
		PlaySound(snd.snd, nextChannel)
		snd.plays += 1
		curPlay[nextChannel] = snd
		
		nextChannel += 1
		If nextChannel >= maxChan
			nextChannel = 0
		EndIf
	End
	
	Method UpdateSounds()
		Debug("Sound Manager")
		Debug("-------------")
		Debug("maxChan: "+maxChan)
		
		For Local i:= 0 Until maxChan
			If ChannelState(i) = 0 And curPlay[i] <> Null
				curPlay[i].plays -= 1
				curPlay[i] = Null
			EndIf
		Next
	End
	
End

Class yimSoundSound
	Field snd:Sound
	Field name:String
	Field plays:Int = 0
	Field looping:Bool = False
	
	Method New(_snd:Sound, _name:String)
		snd = _snd
		name = _name
	End
End

Class yimSoundChannel
	Field chan:Int
	Field snds:List<Sound> = New List<Sound>()
	Field curSnd:Int = 0
	Field numSnds:Int
	Field playOnce:Bool
	
	Method New(_chan:Int, _snds:Sound[], _playOnce:Bool = True)
		chan = _chan
		snds = _snds
		numSnds = snds.Length()
		playOnce = _playOnce
	End
	
	Method Play:Int(loop:Int)
		If ChannelState(chan) = 0
			PlaySound(snds[curSnd], chan, 0)
			curSnd += 1				
			If curSnd = numSnds
				If playOnce
					Return -1
				Else
					curSnd = 0
				EndIf
			EndIf
		EndIf
		
		Return 0
	End
	
	Method Stop()
		StopChannel(chan)
	End
End